<?php

namespace App\Http\Middleware;

use App\Models\Request;
use Closure;
use Illuminate\Support\Facades\Auth;

class RequestLog
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        logger(__METHOD__);
        $user = auth_user();
        $systemInfo = $request->headers->get('x-system-info');
        if (!empty($systemInfo) && is_string($systemInfo)) {
            $systemInfoArr = json_decode($systemInfo, true);
            if (empty($systemInfoArr) || !is_array($systemInfoArr)) {
                parse_str($systemInfo, $systemInfoArr);
            }
        } else {
            $systemInfoArr = [];
        }
        $data = [
            'auth_id' => $user ? $user->id : 0,
            'auth_name' => $user ? $user->name : '',
            'method' => $request->getMethod(),
            'url' => $request->url(),
            'params' => $request->input(),
            'system_info' => $systemInfoArr,
            'ip' => $request->getClientIp(),
            'agent' => $request->userAgent(),
            'referer' => $request->headers->get('Referer'),
        ];
        Request::create($data);
        return $next($request);
    }
}
